package jinyilw.swing.visuals.Jcomp;

import jinyilw.swing.ResourceManager;
import jinyilw.swing.ScreenTools;
import jinyilw.swing.graphics.GraphicsTools;
import jinyilw.swing.image.ImageTools;

import java.awt.Dimension;
import java.awt.Image;
import java.io.File;
import java.net.URL;

public class JActScaleImageComp extends JActImageComp
{
	private static final long serialVersionUID = -1276675463020135887L;
	private static final boolean retina = ScreenTools.isRetina();
	private static final double systemScaleFactor = GraphicsTools
			.getSystemScaleFactor();
	protected Image originImage;
	private final Dimension imageSize = new Dimension();

	public JActScaleImageComp()
	{
	}

	public JActScaleImageComp(URL url)
	{
		setImage(ResourceManager.getBufferedImage(url));
	}

	public JActScaleImageComp(File file)
	{
		setImage(ResourceManager.getBufferedImage(file));
	}

	public JActScaleImageComp(Image image)
	{
		setImage(image);
	}

	public JActScaleImageComp(Image image, Image overImage)
	{
		setImage(image, overImage);
	}

	@Override
	public void setImage(Image img)
	{
		if (originImage != img)
		{
			originImage = image = overImage = img;
			if (img == null)
			{
				if (isShowing())
					repaint();
				return;
			}

			imageSize.width = img.getWidth(null) / 2;
			imageSize.height = img.getHeight(null) / 2;
			if (!retina)
			{
				int ww = (int) (imageSize.width * systemScaleFactor);
				int hh = (int) (imageSize.height * systemScaleFactor);
				image = ImageTools.getShapedImage(img, ww, hh);
			}
			overImage = ImageTools.getContrastLightImage(image, 1.5f, 1.5f);
			if (imageSize.width != getWidth()
					|| imageSize.height != getHeight())
				setSize(imageSize.width, imageSize.height);
			else if (isShowing())
				repaint();
		}
	}

	@Override
	public void setImage(Image image, Image overImage)
	{
		originImage = null;
		this.image = image;
		this.overImage = overImage;
		if (overImage != null && !retina)
		{
			int w = (int) (overImage.getWidth(null) * systemScaleFactor / 2);
			int h = (int) (overImage.getHeight(null) * systemScaleFactor / 2);
			this.overImage = ImageTools.getShapedImage(overImage, w, h);
		}
		if (image != null)
		{
			imageSize.width = image.getWidth(null) / 2;
			imageSize.height = image.getHeight(null) / 2;
			if (!retina)
			{
				int ww = (int) (imageSize.width * systemScaleFactor);
				int hh = (int) (imageSize.height * systemScaleFactor);
				this.image = ImageTools.getShapedImage(image, ww, hh);
			}
		}
		if (imageSize.width != getWidth() || imageSize.height != getHeight())
			setSize(imageSize.width, imageSize.height);
		else if (isShowing())
			repaint();
	}

	@Override
	public Dimension getPreferredSize()
	{
		if (image == null)
			return super.getPreferredSize();
		return new Dimension(imageSize);
	}
}
